#include <math.h>
#include <firmament.h>

#include "driver/barometer/bmp280.h"
#include "hal/barometer/barometer.h"
#include "hal/fmt_spi/fmt_spi_app.h"
#include "qx_hw_spi.h"

/*****************register offset address define*********************/
#define BMP280_TEMP_XLSB        0xFC
#define BMP280_TEMP_LSB         0xFB
#define BMP280_TEMP_MSB         0xFA
#define BMP280_PRESS_XLSB       0xF9
#define BMP280_PRESS_LSB        0xF8
#define BMP280_PRESS_MSB        0xF7
#define BMP280_CONFIG           0xF5
#define BMP280_CRTL_MEAS        0xF4
#define BMP280_STATUS           0xF3
#define BMP280_RESET            0xE0
#define BMP280_ID_ADDR          0xD0
/********************************************************************/

#define BMP280_ID_VALUE         0x58
#define BMP280_RESET_VALUE      0xB6

/********************************************************************/

#define DRV_DBG(...) rt_kprintf(__VA_ARGS__)

static rt_device_t baro_bmp280_spi_dev;


static rt_err_t lowlevel_init(void)
{
    uint8_t chip_id[2] = {0};
    uint8_t reg_val[2] = {0};

    rt_err_t rst = rt_spi_take_bus((struct rt_spi_device *)baro_bmp280_spi_dev);

    if(rst != RT_EOK){
        return RT_ERROR;
    }

    /* check chip id */
    qx_spi_read_reg8(baro_bmp280_spi_dev, BMP280_ID_ADDR, chip_id,sizeof(chip_id));

    if (chip_id[1] != BMP280_ID_VALUE) {
        DRV_DBG("bmp280 wrong chip id:0x%x\n", chip_id);
        return RT_ERROR;
    }

    rst = rt_spi_release_bus((struct rt_spi_device *)baro_bmp280_spi_dev);

    if(rst != RT_EOK){
       return RT_ERROR;
    }

    return RT_EOK;
}

rt_err_t drv_bmp280_init(const char* spi_device_name, const char* baro_device_name)
{
    rt_hw_spi_device_attach("SPIA", spi_device_name, 76);

//    static struct baro_device baro_dev = {
//        .ops = &_baro_ops
//    };

    baro_bmp280_spi_dev = rt_device_find(spi_device_name);

    /* config spi */
    {
        struct rt_spi_configuration cfg;
        cfg.data_width = 8;
        cfg.mode =  RT_SPI_MASTER | RT_SPI_MODE_3 | RT_SPI_MSB; /* SPI Compatible Modes 3 */
        cfg.max_hz = 7000000;

        struct rt_spi_device* spi_device_t = (struct rt_spi_device*)baro_bmp280_spi_dev;
        spi_device_t->config.data_width = cfg.data_width;
        spi_device_t->config.mode = cfg.mode & RT_SPI_MODE_MASK;
        spi_device_t->config.max_hz = cfg.max_hz;

        rt_spi_configure(spi_device_t, &cfg);
    }

    /* device low-level initialization */
    lowlevel_init();
    /* register barometer device */
//    hal_baro_register(&baro_bmp280_spi_dev, baro_device_name, RT_DEVICE_FLAG_RDWR, RT_NULL);

    return RT_EOK;
}
